package com.example.sp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import org.apache.commons.lang3.StringUtils;

public class MainActivity2 extends AppCompatActivity {
    SharedPreferences sp;
    EditText loginName,loginPass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        loginName = findViewById(R.id.loginName);
        loginPass = findViewById(R.id.loginPass);
        CheckBox loginRem = findViewById(R.id.loginRem);

        sp = getSharedPreferences("name_pass", MODE_PRIVATE);
        loadNameAndPassFromPrefence();

        loginRem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    saveNameAndPass2Prefence(loginName.getText().toString(),loginPass.getText().toString());
                }
            }
        });
    }

    private void saveNameAndPass2Prefence(String name, String pass) {
        if(StringUtils.isNotBlank(name) && StringUtils.isNotBlank(pass)){
            SharedPreferences.Editor edit = sp.edit();
            edit.putString("login_name",name);
            edit.putString("login_pass",pass);
            edit.commit();
        }
    }

    private void loadNameAndPassFromPrefence(){
        if(sp != null){
            String name = sp.getString("login_name", "admin");
            String pass = sp.getString("login_pass", "123456");

            if(StringUtils.isNotBlank(name)){
                loginName.setText(name);
            }
            if(StringUtils.isNotBlank(pass)){
                loginPass.setText(pass);
            }

        }
    }
}